package biz.almas.uycnr.crawler.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import biz.almas.uycnr.crawler.dao.factory.MemoryFactory;
import biz.almas.uycnr.crawler.entity.Channel;
import biz.almas.uycnr.crawler.utils.KzWordConvertUtil;
import biz.almas.uycnr.crawler.utils.UyUtil;
import cn.ffcs.memory.BeanHandler;
import cn.ffcs.memory.Memory;

/**
 * @Description: 栏目
 * @Copyright: Copyright (c) 2015 XinJiang Almas Software All Rights Reserved
 * @Company: XinJiang Almas Software
 * @author Ansar786 Nov 19, 2015
 * @version V1.0
 * @history:
 * 
 */
public class ChannelDao {
	// 获取Memory对象
	private Memory memory = MemoryFactory.getInstance();
	// 定义日志输出对象
	private static Logger logger = Logger.getLogger(ChannelDao.class);

	/**
	 * 存储栏目信息 Ansar786 Nov 24, 2015
	 * 
	 * @param channels
	 */
	public void store(List<Channel> channels, int langId) {
		if (channels != null && channels.size() > 0) {
			for (Channel channel : channels) {
				Channel old = getChannelByChnlId(channel.getChnlId(), langId);
				if (old != null) {
					if (!channel.getOperTime().equals(old.getOperTime())) {
						channel.setId(old.getId());
						updateChannel(channel);
						saveChannelByScript(channel, 2);
					}
				} else {
					saveChannel(channel);
					saveChannelByScript(channel, 1);
				}
			}
		}
	}

	/**
	 * Ansar786 Nov 30, 2015
	 * 
	 * @param document
	 * @param lang
	 *            语言分类 1:维文，2：维文ULY，3：维文Selawen，4：哈文，5：哈文Selawen
	 * @param operation
	 *            操作类型：1 表示添加，2 表示修改
	 */
	private void saveChannelByScript(Channel channel, int operation) {
		switch (channel.getLangId()) {
		case 1: // 1：是维文，
			saveOrUpdate(convertToULY(channel), operation);
			saveOrUpdate(convertToSelawen(channel), operation);
			break;
		case 4: // 4：是哈文
//			saveOrUpdate(convertKzToSelawen(channel), operation);
			break;
		default:
			break;
		}
	}
	
	/**
	 * Ansar786 Nov 30, 2015
	 * @param channel
	 * @param operation
	 */
	private void saveOrUpdate(Channel channel, int operation) {
		if (channel != null) {
			if (operation == 1) {
				channel.setId(null);
				saveChannel(channel);
			} else if (operation == 2) {
				updateChannel(channel);
			}
		}
	}

	/**
	 * 添加栏目 Ansar786 Nov 24, 2015
	 * 
	 * @param channel
	 */
	public void saveChannel(Channel channel) {
		try {
			channel.setUpdateTime(new Date());
			memory.create(Channel.class, channel);
		} catch (Exception e) {
			System.out.println(channel);
			logger.error("添加栏目时出错：" + e.toString() + "\n==================");
		}
	}

	/**
	 * 修改栏目 Ansar786 Nov 24, 2015
	 *   
	 * @param channel
	 */
	public void updateChannel(Channel channel) {
		try {
			channel.setUpdateTime(new Date());
			StringBuffer sql = new StringBuffer();
			sql.append("update channel set parent_id = ?, chnl_name = ?, chnl_desc = ?,");
			sql.append("chnl_type = ?, chnl_order = ?, status = ?, documents_url = ?,");
			sql.append("oper_time = ?, crtime = ?, update_time = ?, ");
			sql.append("is_contains_children = ?, show_pic = ? ");
			sql.append("where lang_id = ? and chnl_id = ? ");
			
			List<Object> params = new ArrayList<Object>();
			params.add(channel.getParentId());
			params.add(channel.getChnlName());
			params.add(channel.getChnlDesc());
			params.add(channel.getChnlType());
			params.add(channel.getChnlOrder());
			params.add(channel.getStatus());
			params.add(channel.getDocumentsUrl());
			params.add(channel.getOperTime());
			params.add(channel.getCrtime());
			params.add(channel.getUpdateTime());
			params.add(channel.getIsContainsChildren());
			params.add(channel.getShowPic());
			// where 条件
			params.add(channel.getLangId());
			params.add(channel.getChnlId());

			memory.update(sql, params);
		} catch (Exception e) {
			logger.error("修改栏目时出错：" + e.toString() + "\n=================");
		}
	}

	/**
	 * 获取栏目 Ansar786 Nov 24, 2015
	 * 
	 * @param chnlId
	 * @return
	 */
	public Channel getChannelByChnlId(int chnlId, int langId) {
		try {
			Channel channel = memory.query(
					"select * from channel where chnl_id = ? and lang_id = ?",
					new BeanHandler<Channel>(Channel.class), chnlId, langId);
			if (channel == null) {
				return null;
			}

			return channel;
		} catch (Exception e) {
			logger.error("获取栏目时出错：" + e.toString());
			return null;
		}
	}
	
	private Channel convertToULY(Channel channel) {
		Channel channel2 = channel.clone();
		if (channel2 == null) {
			return null;
		}
		/**
		 * 2 表示维文ULY
		 */
		channel2.setLangId(2);
		channel2.setChnlDesc(UyUtil.toULY(channel2.getChnlDesc()));
		
		return channel2;
	}

	private Channel convertToSelawen(Channel channel) {
		Channel channel2 = channel.clone();
		if (channel2 == null) {
			return null;
		}
		/**
		 * 3：维文Selawen
		 */
		channel2.setLangId(3);
		channel2.setChnlDesc(UyUtil.toSelawen(channel2.getChnlDesc()));
		
		return channel2;
	}
	
	private Channel convertKzToSelawen(Channel channel) {
		Channel channel2 = channel.clone();
		if (channel2 == null) {
			return null;
		}
		
		/**
		 * 5：哈文Selawen
		 */
		channel2.setLangId(5);
		channel2.setChnlDesc(KzWordConvertUtil.toSelawen(channel2.getChnlDesc()));
		
		return channel2;
	}
}
